package com.wdy.async.method.invocation;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

/**
 * @ClassName: App
 * @Description: TODO
 * @Date: 2019/12/30 16:16
 * @Author: wangdy001
 * @Version: 1.0
 */
public class App {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadAsyncExecutor threadAsyncExecutor = new ThreadAsyncExecutor();
        AsyncResult<Integer> integerAsyncResult = threadAsyncExecutor.startProcess(lazyval(20, 3000), callback("test-1"));
        AsyncResult<String> stringAsyncResult = threadAsyncExecutor.startProcess(lazyval("stringtest", 3000), callback("test-2"));
        AsyncResult<Double> doubleAsyncResult = threadAsyncExecutor.startProcess(lazyval(1.2, 4000));

        Thread.sleep(3000);
        System.out.println(integerAsyncResult.getValue());
        System.out.println(stringAsyncResult.getValue());
        doubleAsyncResult.await();
        System.out.println(doubleAsyncResult.getValue());
    }

    private static <T> Callable<T> lazyval(T value, long delayMillis){
        return () -> {
            Thread.sleep(delayMillis);
            return value;
        };
    }

    private static <T> AsyncCallback<T> callback(String name){
        return (v, ex) -> {
            if(ex.isPresent()) {
                System.out.println(name + " execute fail! " + ex.get().getMessage());
            } else {
                System.out.println(name + " execute success! " + v);
            }
        };
    }
}
